package mips.structure;

import java.util.ArrayList;
import java.util.List;

import mips.value.Register;

public class MipsFunc {
    private int stackSize = 0; // 栈大小
    private String name; // 函数名
    public List<MipsBlock> blocks = new ArrayList<>();
    private List<Register> usedRegisters = new ArrayList<>(); // 使用的寄存器

    public MipsFunc(String name) {
        this.name = name;
    }

    public void setStackSize(int stackSize) {
        this.stackSize = stackSize;
    }

    public int getStackSize() {
        return stackSize;
    }

    public String getName() {
        return name;
    }

    public void addRegister(Register register) {
        if (!usedRegisters.contains(register)) {
            usedRegisters.add(register);
        }
    }

    public void removeRegister(Register register) {
        usedRegisters.remove(register);
    }

    public List<Register> getUsedRegisters() {
        return usedRegisters;
    }

    @Override
    public String toString() {
        // 函数名
        StringBuilder sb = new StringBuilder(name + ":\n");
        // 栈大小
        sb.append("addi $sp, $sp, -" + stackSize + "\n");
        sb.append("sw $ra, " + (stackSize - 4) + "($sp)\n");

        // 开始基本块
        for (MipsBlock block : blocks) {
            sb.append(block);
        }
        return sb.toString();
    }
}
